/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.pigeon.utils;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.seppiko.pigeon.exceptions.PigeonHashException;

/**
 * PBKDF2 With Hmac SHA512
 *
 * @author Leonard Woo
 */
public class HashUtil {

  private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA512";
  private static final int ITERATIONS = 1000;
  private static final int KEY_SIZE = 256;

  public static byte[] pbkdf2HmacSHA512(String data, byte[] salt) throws PigeonHashException {
    try {
      return SecretKeyFactory.getInstance(HASH_ALGORITHM)
          .generateSecret(new PBEKeySpec(data.toCharArray(), salt, ITERATIONS, KEY_SIZE))
          .getEncoded();
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
      throw new PigeonHashException("Not found this algorithm or initialization fail", e);
    }
  }
}
